package com.glodon.paas.job.agent.mq;

import java.net.UnknownHostException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.glodon.paas.job.agent.worker.WorkerConfig;
import com.glodon.paas.job.exception.JsonException;
import com.glodon.paas.job.model.MonitorEvent;
import com.glodon.paas.job.model.MonitorEventType;
import com.glodon.paas.job.util.JobUtil;
import com.glodon.paas.job.util.JsonUtil;

public class AgentHeartBeat {
	private static final Logger	monitorLogger		= LoggerFactory.getLogger("monitor");
	private static final Logger	logger				= LoggerFactory.getLogger(AgentHeartBeat.class);

	private static final int	DEFAULT_HEART_BEAT	= 60000;
	private boolean				running				= true;
	private boolean				isStartUp			= true;
	private JmsAgent			agent				= null;

	public AgentHeartBeat(JmsAgent jmsAgent) {
		this.agent = jmsAgent;
	}

	public void start() {
		Thread thread = new Thread() {
			@Override
			public void run() {
				while (running) {
					try {
						sendHeartBeat(isStartUp, agent);
						isStartUp = false;
						Thread.sleep(DEFAULT_HEART_BEAT);
					} catch (Throwable e) {
						// ignores
						logger.warn("send heart beat failure", e.getMessage());
					}
				}
			}
		};
		thread.setDaemon(true);
		thread.start();
	}

	public void sendHeartBeat(boolean isStartUp, JmsAgent agent) throws UnknownHostException {
		MonitorEvent monitorEvent = new MonitorEvent();
		monitorEvent.setType(MonitorEventType.AGENT_STATUS);
		String address = JobUtil.getAddress();
		monitorEvent.setTraceId(address);
		monitorEvent.setStartUp(isStartUp);
		try {
			if (agent.getTask() != null) {
				monitorEvent.addValue("taskInfo", JsonUtil.jsonToMap(agent.getTask().toJson()));
			}
			WorkerConfig[] workerConfigs = agent.getWorkerConfigs();
			if (workerConfigs.length > 0) {
				StringBuilder sb = new StringBuilder();
				int len = workerConfigs.length;
				for (int i = 0; i < len; i++) {
					String type = workerConfigs[i].getType();
					if (type.equals("profile") || type.equals("timeout")) {
						continue;
					}
					sb.append(type);
					if (i < len - 1) {
						sb.append(",");
					}
				}
				monitorEvent.addValue("workerType", sb.toString());
			}
		} catch (JsonException e) {
			e.printStackTrace();
		}
		monitorLogger.info("send heart beat", monitorEvent);
	}

	public void stop() {
		running = false;
	}
}
